package com.gthncz;

import java.io.IOException;
import java.util.Iterator;
import java.util.StringTokenizer;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * WordCount demo
 * @author GT
 * @date 2019-10-22
 */
public class WordCount {
	
	private final static Logger logger = LoggerFactory.getLogger(WordCount.class);
	
	public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {

		private static final IntWritable one = new IntWritable(1);
		private Text word = new Text();
		
		@Override
		public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter)
				throws IOException {
			String line = value.toString();
			StringTokenizer stringTokenizer = new StringTokenizer(line);
			while(stringTokenizer.hasMoreTokens()) {
				String token = stringTokenizer.nextToken();
				word.set(token);
				output.collect(word, one);
				logger.error("Mapper get token: {}", token);
			}
		}
	}
	
	public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {

		@Override
		public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output,
				Reporter reporter) throws IOException {
			logger.error("Reducing {}.", key);
			int sum = 0;
			while (values.hasNext()) {
				sum += values.next().get();
				output.collect(key, new IntWritable(sum));
			}
			logger.error("Reduce {} over.", key);
		}
		
	}

	public static void main(String[] args) throws IOException {
		JobConf jobConf = new JobConf(WordCount.class);
		jobConf.setJobName(WordCount.class.getSimpleName());
		
		jobConf.setMapperClass(Map.class);
		jobConf.setCombinerClass(Reduce.class);
		jobConf.setReducerClass(Reduce.class);
		
		jobConf.setOutputKeyClass(Text.class);
		jobConf.setOutputValueClass(IntWritable.class);
		
		jobConf.setInputFormat(TextInputFormat.class);
		jobConf.setOutputFormat(TextOutputFormat.class);
		
		FileInputFormat.setInputPaths(jobConf, new Path(args[0]));
		FileOutputFormat.setOutputPath(jobConf, new Path(args[1]));
		
		JobClient.runJob(jobConf);
	}

}
